package com.hht.baselibs.activity

import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.hht.baselibs.viewModel.BaseViewModel
import java.lang.reflect.ParameterizedType


/**
 * Author:chen'hu
 * Time:2023/7/31 12:00
 * Description:This is BaseActivity
 */
@RequiresApi(Build.VERSION_CODES.HONEYCOMB)
abstract class BaseActivity<VM : BaseViewModel, DB : ViewDataBinding> : BaseLibActivity<VM, DB>() {

    @RequiresApi(Build.VERSION_CODES.P)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getLayoutResId())
        initFragment(savedInstanceState)
        initViewModel()
        //TODO 必须加上，不然Repository无法感知生命周期
        lifecycle.addObserver(mViewModel.getRepository())
    }

    @RequiresApi(Build.VERSION_CODES.P)
    fun initViewModel() {
        mViewModel = ViewModelProvider(this)[getViewModelClass()]
        initView()
        initObserve()
        bindViewModel()
    }

    //TODO 主要是防止fragment重影问题
    protected open fun initFragment(savedInstanceState: Bundle?) {}

    protected abstract fun getLayoutResId(): Int

    protected open fun initView() {}

    protected open fun initObserve() {}

    //TODO 绑定数据后数据才能生效
    protected open fun bindViewModel() {}

    //动态得到具体的ViewModel名字
//    @RequiresApi(api = Build.VERSION_CODES.P)
//    fun getViewModelClass(): Class<VM> {
//        var xClass = BaseViewModel::class.java as Class<VM>
//        val typeList = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments
//        for (i in typeList.indices) {
//            val typeName = typeList[i].typeName
//            if (typeName.contains("viewModel")) {
//                xClass =
//                    (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[i] as Class<VM>
//                return xClass
//            }
//        }
//        return xClass
//    }

    /**
     * 动态得到具体的ViewModel名字
     */
    private fun getViewModelClass(): Class<VM> {
        val type = javaClass.genericSuperclass as ParameterizedType
        val typeArguments = type.actualTypeArguments
        if (typeArguments.size != 2) {
            throw IllegalStateException("Expected 2 type arguments, but got ${typeArguments.size}")
        }
        // 假设第一个参数是 VM 类型，第二个参数是 DB 类型
        val vmType = typeArguments[0]
        if (vmType is Class<*>) {
            @Suppress("UNCHECKED_CAST")
            return vmType as Class<VM>
        }
        throw IllegalStateException("VM type argument is not a Class instance")
    }


    override fun onDestroy() {
        super.onDestroy()
        lifecycle.removeObserver(mViewModel.getRepository())
    }
}


